#!/usr/bin/python

#calculate charges if file was not yet touched and if label is in second file

from openeye.oechem import *

import amsol_functions


import sys, string, os, os.path, shutil


list = []
new_list = []

solvent = sys.argv[1]

solvent_list = []
print 'test'
#if solvent_list == []:
try:
  sf = open(solvent,'r')
  for i in sf.readlines():
    solvent_list.append(string.strip(i))
    print i
  sf.close()
#else:  
except:
  solvent_list.append(solvent)
 
debug = 'false'

#if cav_term = cav -> apol = apol_wat - apol_hex; sep => don"t substracte anyting, but store the original values
cav_term = sys.argv[2]

#-------------------------------

#MAIN PART 

dir = 'temp_files/'
ifs = oemolistream()
ofs_new_mol2 = oemolostream()
in_dir = 'amsol2/'

mol = OEGraphMol()
file_list = os.listdir(in_dir)
file_list.sort()

for solvent in solvent_list:
 if cav_term == 'cav':
   ext = '_amsol_cav_' + solvent
 elif cav_term == 'sep':
   ext = '_amsol_sep_' + solvent
 else:
   ext = '_amsol_' + solvent


 for file in file_list:
  if not os.path.exists(file[:-5]+ ext) and file[-4:] == 'mol2':
    os.mkdir(file[:-5] + ext)
    os.chdir(file[:-5] + ext)
    os.mkdir(dir)
    
    ifs.open('../' + in_dir + file)
    
    result_tab = open(file[:-5] + '_' + solvent + '.solv' ,'w')
    ofs_new_mol2.open(file[:-5] + ext + '.mol2')
    update_error = open('UpdateCharge.err', 'w')
    
    
    print 'processing file ' + file
 

    while OEReadMolecule(ifs, mol):

       name = mol.GetTitle()
       
       #print name

       amsol_functions.mol2out(mol,dir)
       
       charge = amsol_functions.cal_charge(mol)
       
       amsol_functions.convert2amsol(name, charge, mol, solvent, dir)
      
       amsol_functions.run_amsol()
       
       if solvent <> 'Vac':
       
         amsol_functions.parse_results(name, mol, charge, result_tab, ofs_new_mol2, update_error, cav_term, debug)
       else:

         amsol_functions.parse_results_vac(name, mol, charge, result_tab, ofs_new_mol2, update_error, cav_term)
      
  
    #clean_up  
    result_tab.close()
    update_error.close()
    ofs_new_mol2.close()
    ifs.close()
    if debug == 'false':
      print 'delete files'
      shutil.rmtree(dir,1)
      os.system('rm -f *log')
      os.system('rm -f *.in')
      os.system('rm -f *.out')
      os.system('rm -f core*')
    
    os.chdir('..')
  else:
    print file[:-5] + ext + ' already exists'  
    
    



         
